package ts.group.webapp.market.common.imp.support;

import java.io.File;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.view.AbstractView;

public class JXLSExcelView extends AbstractView {
	public static final String EXCEL_EXPORT_FILE_NAME = "ExcelExportFileName";
	public static final String EXCEL_TEMPLATE_FILE_NAME = "ExcelTemplateFileName";
	
	/** The content type for an Excel response */
	private static final String CONTENT_TYPE = "application/vnd.ms-excel";
	
	private XLSTransformerExt transformer;
	
	/**
	 * Default Constructor.
	 * Sets the content type of the view to "application/vnd.ms-excel".
	 */
	public JXLSExcelView() {
		transformer = new XLSTransformerExt();
		setContentType(CONTENT_TYPE);
	}
	
	@Override
	protected boolean generatesDownloadContent() {
		return true;
	}

	@Override
	protected void renderMergedOutputModel(Map<String, Object> model,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String fileName = (String)model.get(EXCEL_EXPORT_FILE_NAME);
		String templateName = (String)model.get(EXCEL_TEMPLATE_FILE_NAME);
		
		response.setHeader("content-disposition","attachment; filename="+new String(fileName.getBytes("UTF-8"),"ISO8859-1"));
//		response.setHeader("content-disposition","attachment; filename="+new String(fileName.getBytes("gb2312"),"ISO8859-1"));
		
		String realPath = request.getSession().getServletContext().getRealPath("");
		realPath = realPath + File.separator + "resources" + File.separator + templateName;
/*//	String path = request.getClass().getClassLoader().getResource(".").getPath() + "excel/templates/"+templateName;
		String path =  "/resources/excel/templates/"+templateName;
		if(path.startsWith("/")){
			path = path.substring(1);
		}*/
	  	ServletOutputStream out = response.getOutputStream();
	  	transformer.transformXLS(realPath, model, out);

	  	out.flush();
	}

}